import 'package:flutter/material.dart';

/**
 * 自定义连续点击手势识别组件
 * @param key - 控件标识键
 * @param child - 被包裹的子组件
 * @param continuousTapListen - 连续点击事件回调处理器
 */
class ContinuousTapGesture extends GestureDetector {
  final ContinuousTapListen continuousTapListen;

  // ignore: use_key_in_widget_constructors
  ContinuousTapGesture({
    super.key,
    required super.child,
    required this.continuousTapListen,
  }) : super(
    onTap: () {
      continuousTapListen.onTapListening();
    },
  );
}

/**
 * 连续点击事件处理器
 * @param numOfTapsRequired - 触发连续点击所需的最小点击次数（默认1次）
 * @param onContinuousTap - 当满足连续点击条件时的回调函数
 */
class ContinuousTapListen {
  final int numOfTapsRequired;
  final void Function() onContinuousTap;

  int _lastTapTime = 0;
  int _numberOfTapRecord = 0;
  final int _maxMillisecondesBetweenTaps = 300;

  ContinuousTapListen(
      {this.numOfTapsRequired = 1, required this.onContinuousTap});

  /// 处理点击事件的时间序列验证：
  /// 1. 当两次点击间隔超过300ms时重置计数
  /// 2. 有效点击时更新最后点击时间和点击计数器
  /// 3. 达到指定点击次数时触发回调并重置状态
  void onTapListening() {
    final now = DateTime.now().millisecondsSinceEpoch;
    if (_lastTapTime > 0 &&
        now - _lastTapTime >= _maxMillisecondesBetweenTaps) {
      _resetRecord(time: now, count: 1);
    } else {
      _lastTapTime = now;
      _numberOfTapRecord++;
      _checkAvailable();
    }
  }

  /// 重置点击记录状态
  /// @param time - 新的最后点击时间戳
  /// @param count - 新的点击计数器初始值
  void _resetRecord({required int time, required int count}) {
    _lastTapTime = time;
    _numberOfTapRecord = count;
  }

  /// 检查是否满足连续点击条件：
  /// 当记录点击次数达到要求时触发回调并重置状态
  void _checkAvailable() {
    if (_numberOfTapRecord >= numOfTapsRequired) {
      _resetRecord(time: 0, count: 0);
      onContinuousTap();
    }
  }
}